#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import cgi

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext import db
from google.appengine.api import channel
from google.appengine.api import users


class Source(db.Model):
	code = db.TextProperty()
	fileName = db.StringProperty()

class MainHandler(webapp.RequestHandler):
    def get(self):
		user = users.get_current_user()
	
		if not user:
			self.redirect(users.create_login_url(self.request.uri))
		else:
			id = channel.create_channel('save_channel')
			self.response.out.write("""
	<script language="Javascript" type="text/javascript"
src="scripts/CodeMirror-0.92/js/codemirror.js"></script>
	<script type="text/javascript" src="/_ah/channel/jsapi"></script>
	<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.js"></script>
	<link rel="stylesheet" type="text/css" href="scripts/CodeMirror-0.92/css/docs.css"/>
	<body style="padding: 20px;">
	<style type="text/css">
	.CodeMirror-line-numbers {
		width: 2.2em;
		color: #aaa;
		background-color: #eee;
		text-align: right;
		padding: .4em;
		margin: 0;
		font-family: monospace;
		font-size: 10pt;
		line-height: 1.1em;
	}
	</style>
								""")
		self.response.out.write("""
	<body>
		<script>
			channel = new goog.appengine.Channel('{{ channel_id }}');
			socket = channel.open();
			onmessage = onMessage;
			onMessage = function(message)
			{
				url = message.data;
				editor.setCode()
			}
			
			sendMessage = function(code, fileName) {
				code = encodeURI(code);
				var msg = "&" + "c=" + code + "&" + "f=" + fileName + "&i=0";
				if(msg) {
					var xhr = new XMLHttpRequest();
					xhr.open('POST', "/save?channel_id=channel_id" + msg, true);
					xhr.send();
				}
			}
		</script>
		<form id="webeditor" name="webeditor" action="/save" method="post">
			<div style="border: 1px solid black; padding: 3px;">
			<textarea id="code" name="code" cols="100" rows="20" style="width:100%"></textarea></div>
				<fieldset>
					<input type="text" size="48" id="saveName" name="saveName" required placeholder="Enter a valid filename" onblur="sendMessage(editor.getCode(), $('#saveName').val());">
				</fieldset>
		</form>
		<script type="text/javascript"> 
	  		var editor = CodeMirror.fromTextArea("code", {
	    		height: "350px",
	    		parserfile: ["../contrib/python/js/parsepython.js"],
	    		stylesheet: ["scripts/CodeMirror-0.92/contrib/python/css/pythoncolors.css"],
	    		path: "scripts/CodeMirror-0.92/js/",
				lineNumbers: true,
				textWrapping: false,
				indent: 4,
				parserConfig: {'pythonVersion': 2, 'strictErrors': true}
	  			});
		</script>
	</body>
									""")
		sources = db.GqlQuery("SELECT * FROM Source")
		for source in sources:
			if source.code:
				self.response.out.write(source.code)
		


class ChannelHandler(webapp.RequestHandler):
	def post(self):
		channel_id = self.request.get('channel_id')
		if channel_id:
			id = self.request.get('i')
			if (id == '0')
				source = Source()
				source.code = self.request.get('c')
				source.fileName = self.request.get('f')
				source.put()
		else:
			self.response.set_status(401)


class Save(webapp.RequestHandler):
	def post(self):
		source = Source()
		
		source.code = self.request.get('code')
		source.fileName = self.request.get('saveName')
		self.response.out.write(source.code)
		source.put()
		self.redirect('/')
		
class Load(webapp.RequestHandler):
	def post(self):
		channel_id = self.request.get('channel_id')
		if channel_id:
			fileName = self.request.get('f')
			query = GqlQuery("SELECT * FROM Source Where fileName = :1", fileName)

def main():
    application = webapp.WSGIApplication([('/', MainHandler),
										  ('/save', ChannelHandler)],
                                         debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
